<script setup lang="ts">
import {h, onMounted, ref} from 'vue'

import {NButton, NSwitch, useDialog, useMessage} from 'naive-ui'
import {CalendarEdit24Filled, Delete24Filled} from '@vicons/fluent'

import http from '../../utils/http.ts'
import AdvertForm from './AdvertForm.vue'

const message = useMessage()
const dialog = useDialog()


// 列表
onMounted(() => {
  listAdverts()
})

const adverts = ref<AdvertItem[]>([])

async function listAdverts() {
  const d = await http<PageResult<AdvertItem>>({
    url: '/advert/list',
  })
  adverts.value = d.data.list
}

const columns = [{
  type: 'selection',
}, {
  title: '标题',
  key: 'title',
}, {
  title: '内容',
  key: 'content',
}, {
  title: '状态',
  key: 'status',
  render(row: AdvertItem) {
    return switchNode(row)
  },
}, {
  title: '排序',
  key: 'sort',
}, {
  title: '操作',
  key: 'actions',
  align: 'center',
  width: '200',
  render(row: AdvertItem) {
    return [editNode(row.id), deleteNode(row.id)]
  },
}]

// 新增
const advertForm = ref<InstanceType<typeof AdvertForm>>()

function addAdvert() {
  advertForm.value?.init()
}

// 修改
function editNode(id: number) {
  return h(NButton, {
    type: 'success',
    circle: true,
    renderIcon() {
      return h(CalendarEdit24Filled)
    },
    onClick: async () => {
      advertForm.value?.init(id)
    },
  })
}

// # 删除
// 表格行的“删除”按钮
function deleteNode(id: number) {
  return h(NButton, {
    type: 'error',
    circle: true,
    renderIcon() {
      return h(Delete24Filled)
    },
    style: {
      marginLeft: '20px',
    },
    onClick: () => {
      selectedIds.value = [id]
      deleteConfirm('确定删除？')
    },
  })
}
// 待删除的已选择项集合。
// 多选按钮选择的广告id和行删除按钮点击的广告id都是存在这个集合里，都需要先弹出删除确认框，确认后再进行广告的删除。
const selectedIds = ref<number[]>([])
// 勾选按钮触发的事件。勾选好后，再点击“批量删除”按钮可以批量删除选中的广告。
function handleCheck(rowKeys: number[]) {
  selectedIds.value = rowKeys
}
// 弹出删除确认对话框。单个删除和批量删除都要经过“确认”后再进行广告的删除。
function deleteConfirm(dialogMessage: string) {
  if (selectedIds.value.length === 0) return message.info('请选择要删除的记录')
  dialog.warning({
    title: '提示',
    content: dialogMessage,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      deleteBatchBySelectedIds()
    },
    onNegativeClick: () => {
    },
  })
}
// 删除已选择的广告记录
async function deleteBatchBySelectedIds() {
  await http({
    url: '/advert/delete',
    method: 'POST',
    data: selectedIds.value,
  })
  message.success(`[${selectedIds.value}] 删除成功`)
  await listAdverts()
}

// 切换状态
function switchNode(row: AdvertItem) {
  return h(NSwitch, {
    size: 'medium',
    value: row.status,
    async onUpdateValue() {
      const res = await http({
        url: '/advert/update',
        method: 'POST',
        data: {
          id: row.id,
          status: !row.status,
        },
      })
      console.log(res)
      await listAdverts()
      message.success('操作成功')
    },
  })
}
</script>

<template>
  <div class="headerButtons">
    <n-button @click="addAdvert"
              type="primary">
      新增
    </n-button>
    <n-button @click="deleteConfirm('确定批量删除选择的数据？')"
              type="warning">
      批量删除
    </n-button>
  </div>

  <advert-form ref="advertForm" @saved="listAdverts"/>

  <n-data-table
      style="width: 1400px"
      :columns="columns"
      :data="adverts"
      :row-key="(row: AdvertItem)=>row.id"
      @update:checked-row-keys="handleCheck"
      size="large" :bordered="false"
  />
</template>

<style scoped lang="stylus">
$margin-size = 20px

.headerButtons
  margin-bottom $margin-size

  > *:nth-of-type(2)
    margin-left $margin-size
</style>
